//https://leetcode.cn/problems/find-longest-special-substring-that-occurs-thrice-i/description/?envType=daily-question&envId=2024-05-29

class Solution {
public:
    int maximumLength(string s) {
        int n = s.size();
        
        auto judge = [&](int k) -> bool {
            vector<int> res(26, 0);
            unordered_map<int, int> m;
            for (int i = 0; i < k; ++i) {
                ++m[s[i]];
            }
            if (m[s[0]] == k) {
                ++res[s[0] - 'a'];
            }
            for (int i = 0; i < n - k; ++i) {
                --m[s[i]];
                ++m[s[i + k]];
                if (m[s[i + k]] == k) {
                    ++res[s[i + k] - 'a'];
                    if (res[s[i + k] - 'a'] == 3) {
                        return 1;
                    }
                }
            }
            return 0;
        };

        int l = 0, r = n;
        while (l <= r) {
            int m = (l + r) / 2;
            if (judge(m)) {
                l = m + 1;
            }
            else {
                r = m - 1;
            }
        }
        return r ? r : -1;
    }
};